package com.kalaqia.gradle.jiagu

import org.gradle.api.Plugin
import org.gradle.api.Project

class JiaGu360Plugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        project.extensions.create('jiaGu360', JiaGu360Extension)
        project.afterEvaluate {
            def android = project.extensions.android
            android.applicationVariants.all { variant ->
                def variantName = variant.name.capitalize()
                createTask(project, variantName)
            }

            android.buildTypes.all { buildType ->
                def buildTypeName = buildType.name.capitalize()
                createTask(project, buildTypeName)
            }

            android.productFlavors.all { flavor ->
                def flavorName = flavor.name.capitalize()
                createTask(project, flavorName)
            }
            createDownloadTask(project)
        }
    }

    private static void createTask(Project project, variantName) {
        def taskName = "jiaGu360${variantName}"

        def dependsOnTask = project.extensions.jiaGu360.dependsOnTask;

        if (project.tasks.findByPath(taskName) == null) {
            def task = project.task(taskName, type: JiaGu360Task, overwrite: true)
            if (dependsOnTask != null) {
                task.dependsOn "${dependsOnTask}${variantName}"
            }
        }
    }

    private static void createDownloadTask(Project project) {
        def taskName = "download360JiaGu";
        if (project.tasks.findByPath(taskName) == null) {
            project.task(taskName, group: 'jiaGu360', type: DownloadJiaGu360Task, overwrite: true)
        }
    }

}